package com.work.cos.util;

import java.text.NumberFormat;
import java.util.Random;

public class CodeUtils {
	
	/**
	 * 昵称生成
	 * @return
	 */
	public synchronized static String getNickName(String defaultValue){
		Random rm = new Random();
		int strLength = 5;
		// 获得随机数
		double pross = (1 + rm.nextDouble()) * Math.pow(10, strLength);
		// 将获得的获得随机数转化为字符串
		String fixLenthString = String.valueOf(pross);
		String str = defaultValue + "" + fixLenthString.substring(1, strLength + 1);
		try {
			Thread.sleep(10);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return str;
	}
	
	/**
	 * 随机数生成
	 * @return
	 */
	public static String getNumberCode(int length) {
		StringBuffer code = new StringBuffer("");
		for (int i = 0; i < length; i++) {
			code.append((int) (Math.random() * 10));
		}
		return new String(code);
	}
	
	/**
	 * 获取虚拟code
	 * @return
	 */
	public synchronized static String getCode(String defaultValue){
		Random rm = new Random();
		int strLength = 8;
		// 获得随机数
		double pross = (1 + rm.nextDouble()) * Math.pow(10, strLength);
		// 将获得的获得随机数转化为字符串
		String fixLenthString = String.valueOf(pross).replace(".", "");
		String str = defaultValue + "" + fixLenthString.substring(1, strLength + 1);
		try {
			Thread.sleep(10);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return str;
	}
	
	/**
	  * java生成随机数字和字母组合
	  * @param length[生成随机数的长度]
	  * @return
	  */
	public static String getCharAndNumr(int length) {
		String val = "";
		Random random = new Random();
		for (int i = 0; i < length; i++) {
			// 输出字母还是数字
			String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
			// 字符串
			if ("char".equalsIgnoreCase(charOrNum)) {
				// 取得大写字母还是小写字母
				int choice = random.nextInt(2) % 2 == 0 ? 65 : 97;
				val += (char) (choice + random.nextInt(26));
			} else if ("num".equalsIgnoreCase(charOrNum)) { // 数字
				val += String.valueOf(random.nextInt(10));
			}
		}
		return val;
	}
	
	/**
	 * 左补0，位数不足以0代替
	 * @param length
	 * @param number
	 * @return
	 */
	public static String complementLeftZero(int length,int number){
       NumberFormat formatter = NumberFormat.getNumberInstance();  
       formatter.setMinimumIntegerDigits(length);  
       formatter.setGroupingUsed(false);  
       String s = formatter.format(number);
       return s;
	}
}
